<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <input id="search-input" placeholder="搜索关键字" />
    <ul id="suggest-list"></ul>
    <script>
      //https://www.baidu.com/sugrec?prod=pc&wd=hello&cb=jQuery_1684412625594
      //获取输入框的DOM元素
      const searchInput = document.querySelector("#search-input");
      const suggestList = document.querySelector("#suggest-list");
      //给输入框绑定事件输入事件
      searchInput.addEventListener("input", (event) => {
        //获取输入框的值
        const wd = event.target.value;
        ajax({
          url: `https://www.baidu.com/sugrec`, //指定请求的路径
          dataType: "jsonp", //指定数据类型，或者说请求的方式
          jsonp: "cb", //指定传递请求方法的参数名
          data: {
            prod: "pc", //写死的参数
            wd, //传入关键字
          },
        }).then((response) => {
          let html = response.g.map((item) => `<li>${item.q}</li>`).join("");
          suggestList.innerHTML = html;
        });
      });
      function ajax({ url, jsonp, data }) {
        return new Promise(function (resolve, reject) {
          //创建一个临时的变量
          let callbackName = `jQuery_${Date.now()}`;//jQuery_1684412625594
          //创建一个脚本
          let script = document.createElement('script');
          //给window添加全局变量,值是一个回调函数，等jsonp回调回来之后会执行此函数，会把结果传给result
          window[callbackName] = function (result) {
            delete window[callbackName];
            document.body.removeChild(script);
            resolve(result);
          };
          console.log('====================================');
          console.dir(script);
          console.log('====================================');
          script.onerror = (error)=>{
            reject(error);
          }
          //拼出查询字符串
          let search = `?`;//?
          for(let key in data){
            search+=`${key}=${data[key]}&`;//prod=pc&wd=hello&
          }
          search+=`${jsonp}=${callbackName}`;//&cb=jQuery_1684412625594
          script.src = `https://www.baidu.com/sugrec${search}`;
          document.body.appendChild(script);
        });
      }
    </script>
  </body>
</html>
